package com.hsxc.cdz.monitor;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Timer;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.hsxc.cdz.monitor.FSM.CachePile;

@Component
public class ActiveMonitor {
	//主动监视线程
	static Thread am = null;

	//Logger
	private static Logger logger = LoggerFactory.getLogger(ActiveMonitor.class);
	//充电中的电桩列表
	static HashSet<CachePile> activePileList = new HashSet<CachePile>();
	//轮询间隔时间为3分钟
	final static int interval = 3*60*1000;

	@PostConstruct
	public void init(){
		am = new Thread(new ActiveMonitorThread());
		logger.info("ActiveMonitor thread start...");
		am.start();
	}

	@PreDestroy
	public void destroy(){
		am.interrupt();
		logger.info("ActiveMonitor thread destroyed.");
	}

	//添加电桩到链表
	public static void addPileToList(CachePile pile){
		activePileList.add(pile);
		logger.debug("Add pile {} into active pile list, total {} active piles now.", pile.getAddress(), activePileList.size());
	}

	//从链表移出电桩
	public static void delPileFromList(CachePile pile){
		if(!activePileList.contains(pile)){
			logger.warn("Delete a invalid pile from active pile list...");
			return;
		}
		activePileList.remove(pile);
		logger.debug("Delete pile {} from active pile list, total {} active piles now.", pile.getAddress(), activePileList.size());
	}

	//内部线程类
	class ActiveMonitorThread extends Thread {
		@Override
		public void run(){
			//TODO:use global signal to revoke threads
			while(true){
				logger.info("ActiveMonitor start to collect active piles(total {}) status...", activePileList.size());
				
				//遍历正在充电的链表进行状态更新
				Iterator<CachePile> iter = activePileList.iterator();
				while(iter.hasNext()){
					CachePile pile = iter.next();
					logger.debug("ActiveMonitor is collecting status on pile [{}]", pile.getAddress());
					pile.collectStatus();
				}

				//睡眠三分钟
				try{
					sleep(interval);
				}catch(InterruptedException e){
					e.printStackTrace();
					return;
				}
			}
		}
	}
}        

